package cn.flying.cloud.message.core.factory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import cn.flying.cloud.message.core.strategy.MessageSenderStrategy;

/**
 * 短信发送策略工厂
 *
 * @author: admin
 * @date: 2025年03月27日 16:14
 * @version: 1.0
 */
@Component
public class MessageSenderStrategyFactory implements ApplicationContextAware, InitializingBean {
    private final Map<String, MessageSenderStrategy> strategyMap = new ConcurrentHashMap<>();

    private ApplicationContext applicationContext;

    public MessageSenderStrategy getMessageSender(String name) {
        return strategyMap.get(name);
    }

    /**
     * @param applicationContext the ApplicationContext object to be used by this object
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, MessageSenderStrategy> beans = this.applicationContext.getBeansOfType(MessageSenderStrategy.class);
        beans.forEach((k, bean) -> {
            strategyMap.put(bean.getName(), bean);
        });
    }
}
